<script lang="ts" setup>
import type { LowcodeGroovyApi } from '#/api/lowcode/groovy';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createGroovyScript, getGroovyScript, updateGroovyScript } from '#/api/lowcode/groovy';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<LowcodeGroovyApi.GroovyScript>();
const getTitle = computed(() => {
  return formData.value?.id
    ? '编辑脚本'
    : '新建脚本';
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as LowcodeGroovyApi.GroovyScript;
    
    // 如果是编辑模式，确保包含ID
    if (formData.value?.id) {
      data.id = formData.value.id;
    }
    
    try {
      await (formData.value?.id ? updateGroovyScript(data) : createGroovyScript(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success('操作成功');
    } catch (error: any) {
      console.error('操作失败:', error);
      
      let errorMessage = '操作失败，请检查输入信息';
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error?.message) {
        errorMessage = error.message;
      }
      
      message.error(errorMessage);
    } finally {
      modalApi.unlock();
    }
  },
  onCancel() {
    modalApi.close();
  },
  title: getTitle,
  width: '900px',
});

defineExpose({
  modalApi,
});

async function fetchData() {
  if (!formData.value?.id) {
    return;
  }
  try {
    const result = await getGroovyScript(formData.value.id as number);
    
    // 检查响应结构
    let data = result;
    if (result.data) {
      data = result.data;
    }
    
    await formApi.setValues(data);
  } catch (error: any) {
    console.error('Error fetching groovy script:', error);
    
    let errorMessage = '加载脚本详情失败';
    if (error?.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error?.message) {
      errorMessage = error.message;
    }
    
    message.error(errorMessage);
  }
}

modalApi.onOpenChange = async (isOpen: boolean, data?: LowcodeGroovyApi.GroovyScript) => {
  if (isOpen) {
    formData.value = data;
    await fetchData();
  } else {
    // 关闭后重置表单
    await formApi.resetFields();
    formData.value = undefined;
  }
};
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>